<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,initial-scale=1.0">
        <title>侦听器</title>
        <!--第一步：安装Vue.js-->
        <script src="./vue.js"></script>
    </head>
    <body>
        <!--第三步：创建HTML模板（根组件）-->
       <div id="app">
        <p>
            Ask a yes/no question:
            <input v-model="question" :disabled="loading"/>
        </p>
        <p>{{ answer }}</p>
        <div>
            person : {{person}}
        </div>
       </div>
    </body>
    <script>
        //Vue.createApp({/*根组件选项});
        //选项式API
        //第二步：创建Vue的应用实例
        const app = Vue.createApp({
           data(){//定义所需的状态变量
              return{
                  question: '',
                  answer: 'Questions usually contain a question mark. ;-)',
                  loading:false,
                  person: {
                    uname:'zhangsan',
                    age :18,
                    contacts:{
                        cname:'lisi',
                        phone:'15309569776'
                    }
                  }
              }
           },
           watch: {
            question(newVal, oldVal, c){
                console.log('question', newVal, oldVal, c);
                if(newVal.includes('?')){
                    this.getAnswer();
                }
            },
            'person.uname'(newVal,oldVal){//侦听对象中的某个属性
               console.log('person.uname',newVal,oldVal);
            },
            person:{//侦听对象中所有嵌套属性，开启深层侦听：deep属性改为true
                handler(newVal,oldVal){//侦听器被触发后调用的函数
                  console.log('person(深层侦听):', newVal.uname, oldVal.uname);
                  console.log('person(深层侦听):', newVal, oldVal);
                },
                deep :true, //开启深层侦听，默认为false，浅侦听

            }
           },
           methods:{
            async getAnswer(){
                this.loading = true
                this.answer = 'Thinking...'
                try{
                    const res = await fetch('https://yesno.wtf/api')
                    this.answer = (await res.json()).answer
                }catch(error){
                    this.answer = 'Error Could not reach the API. ' + error
                }finally{
                    this.loading = false
                }
            }
           }
        });
      //第四步：在根元素上挂载应用实例，返回根组件实例对象
      const vm = app.mount("#app");//const app = Vue.createApp({}).mount("#app");
    </script>
</html>